//
//  RecommendHomePageViewController.m
//  littleLight's Project-A
//
//  Created by dllo on 16/5/14.
//  Copyright © 2016年 light. All rights reserved.
//

#import "RecommendHomePageViewController.h"
//#import <AFNetworking.h>
#import "WheelPictureModel.h"
#import "CWView.h"
#import "WheelDetailViewController.h"
#import "EveryDayModel.h"
#import "EveryStoryTableViewCell.h"
#import "OriginalFirstModel.h"
#import "ProductModel.h"
#import "OriginalTableViewCell.h"
#import "ProductTableViewCell.h"
#import "SelectAllViewController.h"
#import "EveryDayDetailViewController.h"
#import "ElementsModel.h"
#import "ElementsData.h"
#import "NearlyViewController.h"
#import "ElementsDetailViewController.h"
#import "MyScrollView.h"

#import "HotTripViewController.h"
static NSString *const recommendCell = @"recommendCell";
static NSString *const originalCell = @"originalCell";
static NSString *const productCell = @"productCell";
@interface RecommendHomePageViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *recTableView;
@property (nonatomic, strong) NSMutableArray *recArray;
@property (nonatomic, strong) NSMutableArray *wheelDetailArray;
@property (nonatomic, strong) NSMutableArray *wheelPicArray;
@property (nonatomic, copy) NSString *eveDayString;
@property (nonatomic, strong) NSMutableArray *everyDayArray;
@property (nonatomic, strong) NSMutableArray *sectionOne_countArr;
@property (nonatomic, strong) NSMutableArray *sectionOne_secondArr;
//@property (nonatomic, strong) UITextField *searchTextF;
@property (nonatomic, strong) NSMutableArray *allArray;

@property (nonatomic, strong) MyScrollView *wheelView;
@property (nonatomic, strong) UISearchBar *mySearchBar;
//@property (nonatomic, strong) UISearchDisplayController *searchDC;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSMutableArray *searchArray;
//刷新
   //记录下一页
@property (nonatomic, assign) NSInteger nextPage;
   //判断上拉下拉(yes是上拉)
@property (nonatomic, assign) BOOL isUpLoading;

@end

@implementation RecommendHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.allArray = [NSMutableArray array];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.sectionOne_countArr = [NSMutableArray array];
    self.sectionOne_secondArr = [NSMutableArray array];
    self.everyDayArray = [NSMutableArray array];
    self.wheelPicArray = [NSMutableArray array];
    self.wheelDetailArray = [NSMutableArray array];
    // self.navigationController.navigationBar.translucent = NO;
  
    
//    NSMutableAttributedString *placeHolder = [[NSMutableAttributedString alloc] initWithString:@"搜索目的地、游记、故事集、用户" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
//    [placeHolder addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, placeHolder.length)];
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:192 / 255.0 blue:203 / 255.0 alpha:1];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"发现自己的旅程吧~";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName: [UIFont systemFontOfSize:18],NSFontAttributeName: [UIFont boldSystemFontOfSize:12]}];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStylePlain target:self action:@selector(nearlyAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.recTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49 - 64)  style:UITableViewStylePlain];
    self.recTableView.backgroundColor = [UIColor whiteColor];
   
    [self.view addSubview:self.recTableView];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:192 / 255.0 blue:203 / 255.0 alpha:1];
   
    self.recTableView.delegate = self;
    self.recTableView.dataSource = self;
    [self.recTableView registerClass:[EveryStoryTableViewCell class] forCellReuseIdentifier:recommendCell];
    [self.recTableView registerClass:[OriginalTableViewCell class] forCellReuseIdentifier:originalCell];
    [self.recTableView registerClass:[ProductTableViewCell class] forCellReuseIdentifier:productCell];
    self.recTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.recTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    
    //加载条
    //显示
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

  
    
    self.wheelView = [[MyScrollView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200 *sHeight)];
    self.recTableView.tableHeaderView = self.wheelView;
     __block RecommendHomePageViewController *recVC = self;
    self.wheelView.tapBlock = ^(NSInteger index){
       
    WheelDetailViewController *wheelDVC = [[WheelDetailViewController alloc] init];
    UINavigationController *wheelNa = [[UINavigationController alloc] initWithRootViewController:wheelDVC];
    WheelPictureModel *model = [recVC.wheelDetailArray objectAtIndex:index];
    wheelDVC.webString = model.html_url;
        
    [recVC presentViewController:wheelNa animated:YES completion:^{
                    
                    
    }];
    
    
    };
    

    self.isUpLoading = NO;
    [self addFooter];
    [self addHeader];
    
    
    
    // Do any additional setup after loading the view.
}

#pragma mark --下拉刷新
-(void)addHeader{
    //block中不能使用self,会报错
    __block RecommendHomePageViewController *recommendVC = self;
    
    [self.recTableView addHeaderWithCallback:^{
        //记录页码
        recommendVC.nextPage = 1;
        //标记下拉刷新
        recommendVC.isUpLoading = NO;
        //请求数据
        [recommendVC getDataList:recommendVC.nextPage];
        
    }];
    
    
    //进入程序就开始下拉刷新
    [self.recTableView headerBeginRefreshing];
}

#pragma mark -- 上拉加载更多
-(void)addFooter{
    
    __block RecommendHomePageViewController *recommendVC = self;
    //添加上拉刷新尾部控件
    [self.recTableView addFooterWithCallback:^{
        
        recommendVC.nextPage ++;
        //标记为上拉操作
        recommendVC.isUpLoading = YES;
        //请求数据
        [recommendVC getDataList:recommendVC.nextPage];
        
    }];
    
}

-(void)getDataList:(NSInteger)nextPage{
    
    [XGNetworking XGGETWithURL:@"http://api.breadtrip.com/v2/index/?lat=38.88246119386499&lng=121.5394989362428&sign=f96ac5a452b5be39bd68d3dd055186f5" parameter:nil success:^(id result) {
        NSDictionary *dataDic = [result objectForKey:@"data"];
        NSArray *eleArray = [dataDic objectForKey:@"elements"];
        NSDictionary *wheelDic = [eleArray objectAtIndex:0];
        NSMutableArray *wheelDataArray = [wheelDic objectForKey:@"data"];
        NSArray *xArray = [wheelDataArray firstObject];
        
        
        
        if (self.isUpLoading == NO) {
            [self.wheelDetailArray removeAllObjects];
            [self.wheelPicArray removeAllObjects];
        }
        
        
        for (NSDictionary *dic in xArray) {
            WheelPictureModel *wheelModel = [[WheelPictureModel alloc] init];
            [wheelModel setValuesForKeysWithDictionary:dic];
            [self.wheelPicArray addObject:wheelModel.image_url];
            [self.wheelDetailArray addObject:wheelModel];
            
        }
        [self.wheelView setImages:self.wheelPicArray];
        
        
        NSDictionary *eveTitleDayDic = [eleArray objectAtIndex:1];
        NSArray *eveDataArray = [eveTitleDayDic objectForKey:@"data"];
        NSDictionary *eveTitleDic = [eveDataArray firstObject];
        self.eveDayString = [eveTitleDic objectForKey:@"title"];
        for (NSInteger i = 0; i < eleArray.count; i++) {
            if (1 < i && i < 6) {
                NSDictionary *eveDayDic = eleArray[i];
                NSArray *eveDayArray = [eveDayDic objectForKey:@"data"];
                NSDictionary *yDic = [eveDayArray firstObject];
                EveryDayModel *model = [[EveryDayModel alloc] init];
                [model setValuesForKeysWithDictionary:yDic];
                
                [self.everyDayArray addObject:model];
                //                NSLog(@"========qweqwe===== %@",model.spot_id);
            }
        }
        
        
        
        for (NSDictionary *dic in eleArray) {
            
            
            ElementsModel *elementM = [[ElementsModel alloc] init];
            [elementM setValuesForKeysWithDictionary:dic];
            
            ElementsData *elements = [[ElementsData alloc] init];
            NSDictionary *originalDic = [elementM.data lastObject];
            //            NSLog(@"+++++ ==== %@",originalDic);
            if ([elementM.type integerValue] == 4 || [elementM.type integerValue] == 7) {
                
                NSMutableArray *array = [NSMutableArray array];
                [elements setValuesForKeysWithDictionary:originalDic];
                [array addObject:elements];
                elementM.data = [NSMutableArray arrayWithArray:array];
                //   NSLog(@"====000%@",elements.name);
                // NSLog(@"====1111%@",elements.url);
                
                [self.allArray addObject:elementM];
                
            }
            
            // [self.sectionOne_countArr addObject:elementM];
            
        }
        
        
        
        [self.recTableView footerEndRefreshing];
        [self.recTableView headerEndRefreshing];
        //隐藏加载条
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        [self.recTableView reloadData];
        

        
    } failure:^(NSError *error) {
        NSLog(@"网络请求失败");
        
    } network:^(BOOL networking) {
        NSLog(@"没有网络");
        
        //NSDictionary *dic = [[DataBaseHandle shareDataBaseHandle] readCachePlist:@"RecommendHome"];
        
        //NSDictionary *dataDic = [dic objectForKey:@"data"];
        //NSArray *eleArray = [dataDic objectForKey:@"elements"];
//        NSArray *arr = [[DataBaseHandle shareDataBaseHandle] readCaChePlist:@"firstPageHuanchun"];
//        NSDictionary *wheelDic = [arr objectAtIndex:0];
//        NSMutableArray *wheelDataArray = [wheelDic objectForKey:@"data"];
//        NSArray *xArray = [wheelDataArray firstObject];
//        
//        
//        
//        if (self.isUpLoading == NO) {
//            [self.wheelDetailArray removeAllObjects];
//            [self.wheelPicArray removeAllObjects];
//        }
//        
//        
//        for (NSDictionary *dic in xArray) {
//            WheelPictureModel *wheelModel = [[WheelPictureModel alloc] init];
//            [wheelModel setValuesForKeysWithDictionary:dic];
//            [self.wheelPicArray addObject:wheelModel.image_url];
//            [self.wheelDetailArray addObject:wheelModel];
//            
//        }
//        [self.wheelView setImages:self.wheelPicArray];
//        
//        
//        NSDictionary *eveTitleDayDic = [arr objectAtIndex:1];
//        NSArray *eveDataArray = [eveTitleDayDic objectForKey:@"data"];
//        NSDictionary *eveTitleDic = [eveDataArray firstObject];
//        self.eveDayString = [eveTitleDic objectForKey:@"title"];
//        for (NSInteger i = 0; i < arr.count; i++) {
//            if (1 < i && i < 6) {
//                NSDictionary *eveDayDic = arr[i];
//                NSArray *eveDayArray = [eveDayDic objectForKey:@"data"];
//                NSDictionary *yDic = [eveDayArray firstObject];
//                EveryDayModel *model = [[EveryDayModel alloc] init];
//                [model setValuesForKeysWithDictionary:yDic];
//                
//                [self.everyDayArray addObject:model];
//                //                NSLog(@"========qweqwe===== %@",model.spot_id);
//            }
//        }
//        
//        
//        
//        for (NSDictionary *dic in arr) {
//            
//            
//            ElementsModel *elementM = [[ElementsModel alloc] init];
//            [elementM setValuesForKeysWithDictionary:dic];
//            
//            ElementsData *elements = [[ElementsData alloc] init];
//            NSDictionary *originalDic = [elementM.data lastObject];
//            //            NSLog(@"+++++ ==== %@",originalDic);
//            if ([elementM.type integerValue] == 4 || [elementM.type integerValue] == 7) {
//                
//                NSMutableArray *array = [NSMutableArray array];
//                [elements setValuesForKeysWithDictionary:originalDic];
//                [array addObject:elements];
//                elementM.data = [NSMutableArray arrayWithArray:array];
//                //   NSLog(@"====000%@",elements.name);
//                // NSLog(@"====1111%@",elements.url);
//                
//                [self.allArray addObject:elementM];
//                
//            }
//            
//            // [self.sectionOne_countArr addObject:elementM];
//            
//        }
//        
//        [self.recTableView footerEndRefreshing];
//        [self.recTableView headerEndRefreshing];
//        //隐藏加载条
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        
//        [self.recTableView reloadData];
//   
    }];
    
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.wheelPicArray forKey:@"wheelPicArray"];
    [aCoder encodeObject:self.everyDayArray forKey:@"everyDayArray"];
    [aCoder encodeObject:self.allArray forKey:@"allArray"];
    

}


-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    self = [super init];
    if (self) {
        self.wheelPicArray = [aDecoder decodeObjectForKey:@"wheelPicArray"];
        self.everyDayArray = [aDecoder decodeObjectForKey:@"everyDayArray"];
        self.allArray = [aDecoder decodeObjectForKey:@"allArray"];
    }
    return self;
    
    
}





- (void)nearlyAction:(UIBarButtonItem *)item
{
    NearlyViewController *nearVC = [[NearlyViewController alloc] init];
    UINavigationController *nearNa = [[UINavigationController alloc] initWithRootViewController:nearVC];
    [self presentViewController:nearNa animated:YES completion:^{
        
        
    }];
    
    
    
}

//取消section的吸附效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.recTableView)
    {
        CGFloat sectionHeaderHeight = 60; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 430 * sHeight ;
    }
    return ([UIScreen mainScreen].bounds.size.height - 64 - 49) / 2.5;
    
    
    
}
//设置section的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
  //  UIView *view = [[UIView alloc] init];
//view.backgroundColor = [UIColor orangeColor];
    if (section == 0) {
        UIImageView *imageV = [[UIImageView alloc] init];
        imageV.image = [UIImage imageNamed:@"HomePageSection1"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 5 * 4, 0, [UIScreen mainScreen].bounds.size.width / 5, 55 * sHeight);
        [button setBackgroundImage:[UIImage imageNamed:@"storyAll"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(allButtonAction) forControlEvents:UIControlEventTouchUpInside];
        imageV.userInteractionEnabled = YES;
        [imageV addSubview:button];
        return imageV;
    }
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.image = [UIImage imageNamed:@"HomePageSection2"];
    
    
    
    
    return imageV;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
      
         ElementsModel *model = [self.allArray objectAtIndex:indexPath.row];
        if ([model.type integerValue] == 7) {
            ElementsData *dataModel = [model.data firstObject];
            
            ElementsDetailViewController *eleVC = [[ElementsDetailViewController alloc] init];
            UINavigationController *eleNa = [[UINavigationController alloc] initWithRootViewController:eleVC];
            eleVC.webString = dataModel.url;
            
            [self presentViewController:eleNa animated:YES completion:^{
                
                
            }];
            
        }
        if ([model.type integerValue] == 4) {
            ElementsData *dataModel = [model.data firstObject];
            HotTripViewController *vc = [[HotTripViewController alloc] init];
            vc.myId = dataModel.myId;
            [self.navigationController pushViewController:vc animated:YES];
            
        }

        }
    
    
    
    
    
    
    
    
}






- (void)allButtonAction
{
    SelectAllViewController *allVC = [[SelectAllViewController alloc] init];
    
    UINavigationController *allNa = [[UINavigationController alloc] initWithRootViewController:allVC];

    [self presentViewController:allNa animated:YES completion:^{
   
        
    }];
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 55 * sHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
      if (indexPath.section == 0) {
        EveryStoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:recommendCell];
        cell.array = self.everyDayArray;
        //每日故事精选的点击方法
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
          
          RecommendHomePageViewController *recVC = self;
        cell.Block = ^(EveryDayModel *model){
            
            EveryDayDetailViewController *everyVC = [[EveryDayDetailViewController alloc] init];
            
            UINavigationController *everyNa = [[UINavigationController alloc] initWithRootViewController:everyVC];
            
            everyVC.spot_id = model.spot_id;
            
            [recVC presentViewController:everyNa animated:YES completion:^{
                
                
            }];
      
        };
        cell.backgroundColor = [UIColor colorWithRed:251 / 255.0  green:248 / 255.0 blue:241 / 255.0 alpha:1];
        
        [cell.collectionV reloadData];
        
        
        return cell;
    }
    ElementsModel *model = [self.allArray objectAtIndex:indexPath.row];
   
        if ([model.type integerValue] == 4) {
           
            OriginalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:originalCell];
            ElementsData *firstModel = [model.data lastObject];
            cell.model = firstModel;
           cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        }
            
            ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:productCell];
            ElementsData *firstModel = [model.data lastObject];

            cell.model = firstModel;

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    if (section == 0) {
        return 1;
        
    }
    return self.allArray.count;
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
